import React, { useState, useMemo, useRef, useCallback } from 'react'

export default function (controller) {
    const con = useRef(null)
    const [online, setOnline] = useState(false)
    // 链接
    const connect = useCallback(() => {
        if (con.current) {
            return alert('请先断开链接')
        }

        const socket = new WebSocket('ws://127.0.0.1:3000/ws-chat')
        socket.onopen = function (e) {
            con.current = socket
            setOnline(true)
        }
        socket.onclose = function (e) {
            // alert('close')
            setOnline(false)
            con.current = null
        }
        socket.onmessage = function (e) {
            controller && controller(e.data)
        }
    }, [])
    // 断开链接
    const disconnect = useCallback(() => {
        if (!con.current) {
            return alert('请先链接')
        }
        con.current.close()
    }, [])
    const Bar = useMemo(() => {
        return <div className='con-bar'>
            <span style={{ color: online ? 'green' : 'red' }}>
                {online ? '在线' : '离线'}
            </span>
            <button disabled={online} onClick={connect}>connect</button>
            <button disabled={!online} onClick={disconnect}>disconnect</button>
        </div>
    }, [online])

    return {
        Bar,
        con
    }
}